package models

import (
	"encoding/json"
	"time"
)

type Feedback struct {
	ID        int
	UserId    int
	Type      int
	Phone     int
	Content   string
	Images    string
	CreatedAt time.Time
	UpdatedAt time.Time
}

func (f *Feedback) TableName() string {
	return "feedback"
}

type FeedbackResult struct {
	ID int `json:"id"`
	Phone string `json:"phone"`
	Name string `json:"name"`
	CreatedAt time.Time `json:"created_at"`
	Status int 	`json:"status"`
}

func FeedbackList(status string, phone string, beginTime string,endTime string, page int, pageSize int) ([]*FeedbackResult, *Paginator){
	var result []*FeedbackResult
	model := DB.Table("feedback as f").Select("f.id,u.phone,ud.wechat_name as name,f.created_at,f.status").Joins("left join users as u on u.id=f.user_id").Joins("left join user_detail as ud on ud.user_id=f.user_id ")
	if status != ""{
		model = model.Where("f.status=?", status)
	}
	if phone != ""{
		model = model.Where("u.phone=?", phone)
	}
	if beginTime != "" {
		model = model.Where("f.created_at > ?", beginTime)
	}
	if endTime != "" {
		model = model.Where("f.created_at < ?", endTime)
	}
	var count int
	model.Count(&count)
	paginate := NewPage(page, pageSize, count)
	err := model.Find(&result).Offset(paginate.Offset).Limit(paginate.Limit).Order("r.created_at desc").Error
	if err != nil {
		panic(err)
	}
	return result, &paginate
}

type FeedbackOne struct {
	ID int `json:"id"`
	Phone string `json:"phone"`
	Name string `json:"name"`
	CreatedAt time.Time `json:"created_at"`
	Images string `json:"-"`
	Image interface{} `json:"images"`
	Content string `json:"content"`
	Status int `json:"status"`
	Operation string `json:"operation"`
	Replay string `json:"replay"`

} 
func FeedbackGet(id int) *FeedbackOne{
	var res FeedbackOne
	DB.Table("feedback as f").Select("f.id,u.phone,ud.wechat_name as name,f.created_at,f.images,f.content,f.status,f.operation,f.replay").Joins("left join users as u on u.id=f.user_id").Joins("left join user_detail as ud on ud.user_id=f.user_id").Where("f.id=?",id).Scan(&res)
	json.Unmarshal([]byte(res.Images), &res.Image)
	return &res
}